package com.cauli.manage.config.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.ConvertException;
import cn.hutool.core.util.EnumUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cauli.manage.config.mapper.ConfigMapper;
import com.cauli.manage.config.model.vo.ConfigVO;
import com.cauli.manage.config.model.vo.ConfigDetailVO;
import com.cauli.manage.config.model.dto.ConfigQueryDTO;
import com.cauli.manage.config.model.dto.ConfigUpdateDTO;
import com.cauli.manage.config.model.entity.Config;
import com.cauli.manage.config.service.ConfigService;
import com.cauli.utils.exception.MyException;
import com.cauli.utils.util.EnumConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Cauli
 * @date 2022-12-14 17:01:10
 * @description 系统设置表 服务实现类
 */
@Slf4j
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {
    @Override
    public Page<Config> getConfigPage(ConfigQueryDTO configQueryDTO) {
        return baseMapper.selectPage(configQueryDTO.toPage(), configQueryDTO.toLambdaQueryWrapper());
    }

    @Override
    public ConfigVO getConfigById(Long configId) {
        Config config = baseMapper.selectById(configId);
        ConfigVO configVO = new ConfigVO();
        if (config != null) {
            BeanUtils.copyProperties(config, configVO);
        }
        return configVO;
    }

    @Override
    public void updateConfig(ConfigUpdateDTO configUpdateDTO) {
        // 根据系统设置ID获取系统设置信息
        Config config = baseMapper.selectById(configUpdateDTO.getConfigId());
        BeanUtil.copyProperties(configUpdateDTO, config);
        if (config == null) {
            throw new MyException("系统设置不存在");
        }
        baseMapper.updateById(config);
    }

    public ConfigDetailVO getConfig(ConfigQueryDTO configQueryDTO) {
        ConfigDetailVO configDetailVO = new ConfigDetailVO();
        List<Config> configList = new ArrayList<>();
        if (configQueryDTO != null) {
            LambdaQueryWrapper<Config> configLambdaQueryWrapper = configQueryDTO.toLambdaQueryWrapper();
            configList = baseMapper.selectList(configLambdaQueryWrapper);
        } else {
            configList = baseMapper.findAll();
        }

        for (Config config : configList) {
            String key = config.getConfigName();
            try {
                Field field = ConfigDetailVO.class.getDeclaredField(key);
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                String configValue = config.getConfigValue();

                Object convertVal;
                if (EnumUtil.isEnum(fieldType)) {
                    convertVal = EnumConvertUtils.convertStrToEnum(fieldType, configValue);
                } else {
                    convertVal = Convert.convert(fieldType, configValue);
                }
                field.set(configDetailVO, convertVal);
            } catch (NoSuchFieldException | IllegalAccessException | ConvertException e) {
                log.error("通过反射, 将字段 {} 注入configDTO时出现异常：", key, e);
            }
        }
        return configDetailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConfig(ConfigDetailVO configDetailVO) {
        List<Config> configList = new ArrayList<>();

        Field[] fields = ConfigDetailVO.class.getDeclaredFields();
        for (Field field : fields) {
            String key = field.getName();
            Config config = baseMapper.findByName(key);
            if (config != null) {
                field.setAccessible(true);
                Object val = null;

                try {
                    val = field.get(configDetailVO);
                } catch (IllegalAccessException e) {
                    log.error("通过反射，从ConfigDTO获取字段 {} 时出现异常：", key, e);
                }

                if (val != null) {
                    // 如果是枚举类型, 则取value值
                    if (EnumUtil.isEnum(val)) {
                        val = EnumConvertUtils.convertEnumToStr(val);
                    }
                    config.setConfigValue(Convert.toStr(val));
                    configList.add(config);
                }
            }
        }
        configList.forEach(config -> baseMapper.updateById(config));
    }
}




